package com.pirestupppai.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.pirestupppai.R;
import com.pirestupppai.adapter.StaggeredAdapter;
import com.pirestupppai.base.BaseActivity;
import com.pirestupppai.base.BaseStatus;
import com.pirestupppai.bean.FeedItem;
import com.pirestupppai.common.Constant;
import com.pirestupppai.network.NetworkRequest;
import com.pirestupppai.network.TupaiSubscriber;
import com.pirestupppai.widgets.helper.SpacesItemDecoration;
import com.pirestupppai.widgets.view.LoadMoreFooter;
import com.pirestupppai.widgets.view.TagDetailAskView;
import com.pirestupppai.widgets.view.TitleBar;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * 标签详情列表
 *
 * @author: xiaoluo
 * @date: 2017-04-20 10:50
 */
public class TagDetailActivity extends BaseActivity {

    @BindView(R.id.staggered_recycler_view)
    RecyclerView recyclerView;
    @BindView(R.id.staggered_swipe_layout)
    SwipeRefreshLayout swipeRefreshLayout;
    @BindView(R.id.staggered_title_bar)
    TitleBar titleBar;

    private RelativeLayout mAskLayout;
    private LinearLayout mAskLinear;
    private TextView mReplyTitleTv;
    private HorizontalScrollView mScrollView;

    private LoadMoreFooter mFooterView;
    private View mHeaderView;
    private StaggeredAdapter mStaggeredAdapter;
    private StaggeredGridLayoutManager mStaggeredGridLayoutManager;

    private int mPosition = 0;  // 列表最后一位
    private int mPage = 1;
    private int mSize = 15;
    private int mId;
    private boolean hasMore = true;
    private List<FeedItem> mStaggeredList = new ArrayList<>();
    private List<FeedItem> mAskList = new ArrayList<>();
    private String mType = Constant.TYPE_REPLY;
    private String mTitle;

    @Override
    protected Context getActivityContext() {
        return this;
    }

    @Override
    protected int loadParentLayout() {
        return R.layout.activity_staggered;
    }

    @Override
    protected void initViews() {
        mType = getIntent().getStringExtra(Constant.IntentKey.STAGGERED_TYPE);
        mTitle = getIntent().getStringExtra(Constant.IntentKey.TITLE);
        mId = getIntent().getIntExtra(Constant.IntentKey.ID, -1);

        titleBar.setTitle(mTitle);

        mFooterView = new LoadMoreFooter(mContext);
        mHeaderView = LayoutInflater.from(mContext).inflate(R.layout.view_staggered_header, null);
//        swipeRefreshLayout.setColorSchemeColors(ContextCompat.getColor(mContext, R.color.colorAccent));

        mStaggeredAdapter = new StaggeredAdapter(mContext, mStaggeredList);
        mStaggeredAdapter.setFooterView(mFooterView);
        mStaggeredGridLayoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);

        recyclerView.setLayoutManager(mStaggeredGridLayoutManager);
        recyclerView.setAdapter(mStaggeredAdapter);
        recyclerView.setHasFixedSize(true);
        recyclerView.addItemDecoration(new SpacesItemDecoration(16));  // 间隔

        mStaggeredAdapter.setHeaderView(mHeaderView);
        mAskLayout = (RelativeLayout) mHeaderView.findViewById(R.id.staggered_ask_layout);
        mAskLinear = (LinearLayout) mHeaderView.findViewById(R.id.staggered_ask_linear);
        mReplyTitleTv = (TextView) mHeaderView.findViewById(R.id.reply_title_tv);
        mScrollView = (HorizontalScrollView) mHeaderView.findViewById(R.id.ask_scroll_view);

        if (mType.equals(Constant.TYPE_REPLY)) {
            mAskLayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(mContext, TagDetailActivity.class);
                    intent.putExtra(Constant.IntentKey.STAGGERED_TYPE, Constant.TYPE_ASK);
                    intent.putExtra(Constant.IntentKey.TITLE, mTitle);
                    intent.putExtra(Constant.IntentKey.ID, mId);
                    startActivity(intent);
                }
            });
            getAskData();
        } else {
            mAskLayout.setVisibility(View.GONE);
            mScrollView.setVisibility(View.GONE);
        }
    }

    @Override
    protected void initListeners() {
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getData(BaseStatus.REFRESH);
            }
        });

        // 监听到达底部事件
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                //到达底部时,加载更多
                int[] lastVisiblePosition = mStaggeredGridLayoutManager.findLastCompletelyVisibleItemPositions(new int[2]);
                if (mStaggeredGridLayoutManager.getChildCount() > 0
                        && mStaggeredGridLayoutManager.getItemCount() >= mStaggeredGridLayoutManager.getChildCount()
                        && lastVisiblePosition[1] + 1 >= mStaggeredGridLayoutManager.getItemCount()
                        && dy > 0) {
                    mPosition = lastVisiblePosition[1] + 1;
                    if (hasMore) {
                        mFooterView.setStatus(LoadMoreFooter.Status.LOADING);
                        getData(BaseStatus.LOADMORE);
                    }
                }

                // 防止滑到列表中间时，下拉引起下拉刷新
                if (swipeRefreshLayout.isRefreshing()) {
                    swipeRefreshLayout.setEnabled(true);
                } else {
                    int topRowVewrticalPosition =
                            (recyclerView == null || recyclerView.getChildCount() == 0) ? 0 : recyclerView.getChildAt(0).getTop();
                    swipeRefreshLayout.setEnabled(topRowVewrticalPosition >= 0);
                }
            }
        });
    }

    @Override
    protected void initLogic() {
        // 进入界面就刷新
        swipeRefreshLayout.post(new Runnable() {
            @Override
            public void run() {
                getData(BaseStatus.REFRESH);
                swipeRefreshLayout.setRefreshing(true);
            }
        });
    }

    @Override
    public void onClick(View v) {

    }

    /**
     * 获取最新求P数据
     */
    private void getAskData() {
        NetworkRequest.getInstance().getTagDetailList(mId, Constant.TYPE_ASK, 1, 20, this,
                new TupaiSubscriber<List<FeedItem>>(mContext) {
                    @Override
                    protected void requestSuccess(List<FeedItem> feedItems) {
                        if ((feedItems != null && feedItems.size() == 0) || feedItems == null) {
                            mScrollView.setVisibility(View.GONE);
                            mAskLayout.setVisibility(View.GONE);
                            return;
                        }

                        mAskList.clear();
                        mAskList.addAll(feedItems);
                        setAskViews();
                    }

                    @Override
                    protected void requestError(String error) {

                    }
                });
    }


    /**
     * 设置求P视图
     */
    private void setAskViews() {
        mAskLinear.removeAllViews();
        for (int i = 0; i < mAskList.size(); i++) {
            TagDetailAskView view = new TagDetailAskView(mContext, mAskList.get(i));
            mAskLinear.addView(view);
        }
    }

    /**
     * 获取数据
     */
    private void getData(final BaseStatus status) {
        if (status == BaseStatus.REFRESH) {
            mFooterView.setStatus(LoadMoreFooter.Status.GONE);
            hasMore = true;
            mPage = 1;
        } else {
            mPage++;
        }

        NetworkRequest.getInstance().getTagDetailList(mId, mType, mPage, mSize, this,
                new TupaiSubscriber<List<FeedItem>>(mContext) {
                    @Override
                    protected void requestSuccess(List<FeedItem> feedItems) {
                        if (feedItems != null && feedItems.size() != 0) {
                            if (status == BaseStatus.REFRESH) {
                                mReplyTitleTv.setVisibility(View.VISIBLE);
                                mStaggeredList.clear();
                                mStaggeredList.addAll(feedItems);
                                mStaggeredAdapter.notifyDataSetChanged();
                            } else {
                                mStaggeredList.addAll(feedItems);
                                mStaggeredAdapter.notifyItemInserted(mPosition);
                                mFooterView.setStatus(LoadMoreFooter.Status.GONE);
                            }
                        } else {
                            mFooterView.setStatus(LoadMoreFooter.Status.THE_END);
                        }
                        swipeRefreshLayout.setRefreshing(false);

                        if (feedItems != null && feedItems.size() < mSize) {
                            mFooterView.setStatus(LoadMoreFooter.Status.THE_END);
                            hasMore = false;
                        }
                    }

                    @Override
                    protected void requestError(String error) {
                        swipeRefreshLayout.setRefreshing(false);
                        if (status == BaseStatus.LOADMORE) {
                            mFooterView.setStatus(LoadMoreFooter.Status.GONE);
                            mPage--;
                        }
                    }
                });

    }
}
